<template>
  <CrudTable
    :buttons="tableButtons"
    row-selection-type="multiple"
    :columns="tableColumns"
    @currentChange="handleSelectChange"
    :tableData="pageData.tableData.records"
    :loading="pageData.loading"
    :pagination="pageData.pagination"
    @pageChange="handlePageChange"
    @rowDbClick="handleRowDbClick"
    :showRefresh="true"
    :showExport="false"
    @refreshData="handleTableRefresh"
  >
    <template #operations>
      <InputSelect
        placeholder="点击右侧图标选择资方信息进行搜索"
        :value="pageData.filterValue.funderName"
        @onClick="handleFunderShow"
      />
      <InputSelect
        placeholder="点击右侧图标选择国外主体信息进行搜索"
        :value="pageData.filterValue.funderGlobalMainPartName"
        @onClick="handleMainPartShow"
      />
      <t-space size="small">
        <t-button theme="primary" @click="filterChange">查询</t-button>
        <t-button theme="warning" @click="handleFilterReset">重置</t-button>
      </t-space>
    </template>
    <template #rowOperations="{ row }">
      <div class="crud-table__row_operations">
        <t-link variant="text" theme="primary" @click="handleOperateRow('view', row)">查看</t-link>
        <t-link variant="text" theme="primary" @click="handleOperateRow('edit', row)">修改</t-link>
        <t-link variant="text" theme="danger" @click="handleOperateRow('delete', row)">删除</t-link>
      </div>
    </template>
  </CrudTable>

  <EditForm
    v-if="pageData.showEditForm"
    :dialogVisible="pageData.showEditForm"
    :mode="pageData.editFormMode"
    :id="pageData.selectedRowId"
    @close="handleDialogClose"
  />

  <SelectTable
    v-if="pageData.funder.show"
    :loading="pageData.funder.loading"
    title="选择资方"
    :showDialog="pageData.funder.show"
    width="60vw"
    rowSelectionType="single"
    :tableData="pageData.funder.data.records"
    :columns="funderColumns"
    @onConfirm="handleFunderConfirm"
    @onCancel="handleFunderClose"
    :pagination="pageData.funder.pagination"
    @page-change="handleFunderPageChange"
    :filter-value="pageData.funder.filterValue"
    @filter-change="handleFunderFilterChange"
  />

  <SelectTable
    v-if="pageData.mainPart.show"
    :loading="pageData.mainPart.loading"
    title="选择国外主体"
    :showDialog="pageData.mainPart.show"
    width="60vw"
    rowSelectionType="single"
    tableMaxHeight="32vh"
    :tableData="pageData.mainPart.data.records"
    :columns="mainPartColumns"
    placement="center"
    @onConfirm="handleMainPartConfirm"
    @onCancel="handleMainPartClose"
    :pagination="pageData.mainPart.pagination"
    @page-change="handleMainPartPageChange"
  >
    <template #toolkit>
      <t-form class="crud-form" :data="pageData.mainPart.filterValue">
        <t-space direction="vertical" style="width: 100%" size="small">
          <t-row>
            <t-col :span="6">
              <t-form-item :labelWidth="120" label="中文主体名称" name="customerName">
                <t-input
                  maxlength="50"
                  v-model="pageData.mainPart.filterValue.customerName"
                  placeholder="请输入中文主体名称进行筛选"
                />
              </t-form-item>
            </t-col>
            <t-col :span="6">
              <t-form-item :labelWidth="120" label="英文主体名称" name="englishName">
                <t-input
                  maxlength="50"
                  v-model="pageData.mainPart.filterValue.englishName"
                  placeholder="请输入英文主体名称进行筛选"
                />
              </t-form-item>
            </t-col>
          </t-row>
          <t-row>
            <t-col :span="6">
              <t-form-item :labelWidth="120" label="英文昵称" name="englishNickname">
                <t-input
                  maxlength="50"
                  v-model="pageData.mainPart.filterValue.englishNickname"
                  placeholder="请输入英文主体昵称进行筛选"
                />
              </t-form-item>
            </t-col>
            <t-col :span="6">
              <t-form-item :labelWidth="120" label="所属地区" name="countryId">
                <InputSelect
                  :value="pageData.mainPart.filterValue.countryName"
                  placeholder="点击右边按钮选择国家/地区"
                  @onClick="handleRegionShow"
                />
              </t-form-item>
            </t-col>
          </t-row>

          <div class="crud-form__operations">
            <t-button theme="primary" @click="handleMainPartFilterChange">查询</t-button>
            <t-button theme="warning" @click="handleMainPartFilterReset">重置</t-button>
          </div>
        </t-space>
      </t-form>
    </template>
  </SelectTable>

  <SelectTable
    v-if="pageData.region.show"
    :loading="pageData.region.loading"
    title="选择国家/地区"
    :showDialog="pageData.region.show"
    width="60vw"
    rowSelectionType="single"
    :zIndex="2600"
    :tableData="pageData.region.data.records"
    :columns="regionColumns"
    @onConfirm="handleRegionConfirm"
    @onCancel="handleRegionClose"
    :pagination="pageData.region.pagination"
    @page-change="handleRegionPageChange"
    :filter-value="pageData.region.filterValue"
    @filter-change="handleRegionFilterChange"
  />
</template>

<script lang="tsx" setup>
// 框架和组件库
import { computed, reactive, defineAsyncComponent } from "vue";
import { DialogPlugin, MessagePlugin } from "tdesign-vue-next";

// TS 类型文件
import type { ICrudTableDataPage, ISelectTableGroups } from "@/types";

// 工具函数
import { http } from "@/utils/fetch";

// 常量
import { FMR_FIND_ALL } from "@/api/merchants";
import { PAGINATION_VALUE } from "@/common/constants";

// API
import { getRegionList } from "@/api/region";
import { getFunderList, getMainPartList } from "@/api/merchants";

// 业务数据
import { tableColumns as funderColumns } from "@/pages/Dashboard/Merchants/Funder/components/columns";
import { tableColumns as mainPartColumns } from "@/pages/Dashboard/Merchants/MainPart/components/columns";
import { tableColumns as regionColumns } from "@/pages/Dashboard/Info/Region/components/columns";
import { tableColumns } from "./components/columns";

// 动态组件
const EditForm = defineAsyncComponent(() => import("./components/EditForm.vue"));

const GET_LIST_PATH = FMR_FIND_ALL; // 查询信息接口
const DELETE_ITEM_PATH = "/funder/relatedInfo/delete"; // 删除接口

const pageData = reactive({
  loading: false,
  tableData: {} as ICrudTableDataPage,
  selectedRow: {},
  selectedRowId: "",
  selectedRowsEvent: {},
  showEditForm: false,
  editFormMode: "",
  filterValue: {
    funderId: "",
    funderName: "",
    funderGlobalMainPartId: "",
    funderGlobalMainPartName: ""
  },
  pagination: {
    pageSize: 20,
    total: 0,
    current: 1
  },
  funder: {
    show: false,
    loading: false,
    data: {},
    filterValue: {},
    pagination: {
      pageSize: 20,
      total: 0,
      current: 1
    }
  } as ISelectTableGroups,
  mainPart: {
    show: false,
    loading: false,
    data: {},
    filterValue: {
      customerName: "",
      englishName: "",
      englishNickname: "",
      countryId: "",
      countryName: ""
    },
    pagination: {
      pageSize: 20,
      total: 0,
      current: 1
    }
  } as ISelectTableGroups,
  region: {
    show: false,
    loading: false,
    data: {},
    filterValue: {
      countryName: ""
    },
    pagination: {
      pageSize: 20,
      total: 0,
      current: 1
    }
  } as ISelectTableGroups
});

// 表格操作按钮配置
const tableButtons = computed(() => [
  {
    name: "新增",
    click: () => {
      handleOperateRow("new");
    }
  }
]);

// 获取列表数据
const findAllList = async () => {
  pageData.loading = true;
  const resultData = await http(
    "POST",
    `${GET_LIST_PATH}?currentPage=${pageData.pagination.current}&pageSize=${pageData.pagination.pageSize}`,
    pageData.filterValue
  );
  if (resultData.code === 200) {
    pageData.tableData = resultData.data;
    pageData.pagination.total = resultData.data.total;
    pageData.pagination.current = resultData.data.current;
    pageData.pagination.pageSize = resultData.data.size;
    pageData.loading = false;
  }
};

const handlePageChange = (pageInfo: Record<string, any>) => {
  pageData.pagination.pageSize = pageInfo.pageSize;
  pageData.pagination.current = pageInfo.current;
  findAllList();
};

// 资方的选择列表方法
const getFunderData = async () => {
  pageData.funder.loading = true;
  const resultData = await getFunderList(
    pageData.funder.pagination.current,
    pageData.funder.pagination.pageSize,
    pageData.funder.filterValue
  );
  if (resultData.code === 200) {
    pageData.funder.data = resultData.data;
    pageData.funder.pagination.total = resultData.data.total;
    pageData.funder.pagination.current = resultData.data.current;
    pageData.funder.pagination.pageSize = resultData.data.size;
    pageData.funder.loading = false;
  }
};

const handleFunderConfirm = (e: Record<string, any>) => {
  pageData.filterValue.funderId = e.options.currentRowData.id;
  pageData.filterValue.funderName = e.options.currentRowData.companyName;
  handleFunderClose();
};

const handleFunderShow = () => {
  pageData.funder.show = true;
  getFunderData();
};
const handleFunderClose = () => {
  pageData.funder.show = false;
};

const handleFunderFilterChange = (filters: Record<string, any>) => {
  pageData.funder.filterValue = filters;
  pageData.funder.pagination = structuredClone(PAGINATION_VALUE);
  getFunderData();
};

const handleFunderPageChange = (pageInfo: Record<string, any>) => {
  pageData.funder.pagination.pageSize = pageInfo.pageSize;
  pageData.funder.pagination.current = pageInfo.current;
  getFunderData();
};

// 国外主体的的选择列表方法
const getMainPartData = async () => {
  pageData.funder.loading = true;
  const resultData = await getMainPartList(
    pageData.mainPart.pagination.current,
    pageData.mainPart.pagination.pageSize,
    pageData.mainPart.filterValue
  );
  if (resultData.code === 200) {
    pageData.mainPart.data = resultData.data;
    pageData.mainPart.pagination.total = resultData.data.total;
    pageData.mainPart.pagination.current = resultData.data.current;
    pageData.mainPart.pagination.pageSize = resultData.data.size;
    pageData.mainPart.loading = false;
  }
};

const handleMainPartConfirm = (e: Record<string, any>) => {
  pageData.filterValue.funderGlobalMainPartId = e.options.currentRowData.id;
  pageData.filterValue.funderGlobalMainPartName = e.options.currentRowData.customerName;
  handleMainPartClose();
};

const handleMainPartShow = () => {
  pageData.mainPart.show = true;
  getMainPartData();
};
const handleMainPartClose = () => {
  pageData.mainPart.show = false;
};

const handleMainPartFilterChange = () => {
  pageData.mainPart.pagination = structuredClone(PAGINATION_VALUE);
  getMainPartData();
};

const handleMainPartFilterReset = () => {
  pageData.mainPart.pagination = structuredClone(PAGINATION_VALUE);
  pageData.mainPart.filterValue = {
    customerName: "",
    englishName: "",
    englishNickname: "",
    countryId: "",
    countryName: ""
  };
  getMainPartData();
};

const handleMainPartPageChange = (pageInfo: Record<string, any>) => {
  pageData.mainPart.pagination.pageSize = pageInfo.pageSize;
  pageData.mainPart.pagination.current = pageInfo.current;
  getMainPartData();
};

// 国家地区选择列表方法
const getRegionData = async () => {
  pageData.region.loading = true;
  const resultData = await getRegionList(
    pageData.region.pagination.current,
    pageData.region.pagination.pageSize,
    pageData.region.filterValue
  );
  if (resultData.code === 200) {
    pageData.region.data = resultData.data;
    pageData.region.pagination.total = resultData.data.total;
    pageData.region.pagination.current = resultData.data.current;
    pageData.region.pagination.pageSize = resultData.data.size;
    pageData.region.loading = false;
  }
};

const handleRegionConfirm = (e: Record<string, any>) => {
  pageData.mainPart.filterValue.countryId = e.options.currentRowData.id;
  pageData.mainPart.filterValue.countryName = e.options.currentRowData.countryName;
  handleRegionClose();
};

const handleRegionShow = () => {
  pageData.region.show = true;
  getRegionData();
};
const handleRegionClose = () => {
  pageData.region.show = false;
};

const handleRegionFilterChange = (filters: Record<string, any>) => {
  pageData.region.filterValue = filters;
  pageData.region.pagination = structuredClone(PAGINATION_VALUE);
  getRegionData();
};

const handleRegionPageChange = (pageInfo: Record<string, any>) => {
  // console.log(pageInfo, newDataSource);
  pageData.region.pagination.pageSize = pageInfo.pageSize;
  pageData.region.pagination.current = pageInfo.current;
  getRegionData();
};

const handleRowDbClick = (context: Record<string, any>) => {
  handleOperateRow("view", context.row);
};

const handleOperateRow = (mode: string, row?: Record<string, any>) => {
  if (mode !== "delete") {
    if (mode === "new") {
      pageData.selectedRow = {};
      pageData.selectedRowId = "";
    } else {
      pageData.selectedRow = row!;
      pageData.selectedRowId = row!.id;
    }
    pageData.editFormMode = mode;
    pageData.showEditForm = true;
  } else if (mode === "delete") {
    const confirmDialog = DialogPlugin({
      header: "警告",
      body: "确定要删除这一条数据吗？",
      confirmBtn: "确定",
      cancelBtn: "取消",
      theme: "warning",
      onConfirm: async () => {
        const deleteData = await http("DELETE", `${DELETE_ITEM_PATH}?id=${row!.id}`);
        if (deleteData.code === 200) {
          MessagePlugin.success("删除成功！");
          findAllList();
          confirmDialog.hide();
        }
      },
      onClose: () => {
        confirmDialog.hide();
      }
    });
  } else {
    MessagePlugin.error("错误：未知的表格操作模式。");
  }
};

const handleSelectChange = (e: Record<string, any>) => {
  pageData.selectedRowsEvent = e;
};

// 过滤事件触发函数
const filterChange = () => {
  pageData.pagination = structuredClone(PAGINATION_VALUE);
  findAllList();
};

const handleFilterReset = () => {
  pageData.pagination = structuredClone(PAGINATION_VALUE);
  pageData.filterValue = { funderId: "", funderName: "", funderGlobalMainPartId: "", funderGlobalMainPartName: "" };
  findAllList();
};

const handleTableRefresh = () => {
  pageData.selectedRow = {};
  pageData.selectedRowId = "";
  pageData.pagination = structuredClone(PAGINATION_VALUE);
  pageData.filterValue = { funderId: "", funderName: "", funderGlobalMainPartId: "", funderGlobalMainPartName: "" };
  findAllList();
};

// 对话框关闭时的处理函数
const handleDialogClose = (e: string) => {
  if (e === "success") {
    MessagePlugin.success("操作成功！");
    findAllList();
  }
  pageData.showEditForm = false;
};

// 初始化列表
findAllList();
</script>
